import { createRouter, createWebHistory } from "vue-router";
import Cookies from 'js-cookie'
let login = () => import('@/views/Login.vue')
let Index = () => import('@/views/Index.vue')
let _404 = () => import('@/views/404.vue')
import page from "./page.js";


const routes = [
  {
    path: "/",
    redirect: "/index"
  },
  {
    path: "/login",
    name: "Login",
    component: login,
  },
  {
    path: "/index",
    name: "Index",
    component: Index,
    meta: {
      title: 'home'
    },
    children: [...page,
    {
      path: 'userinfo',
      name: 'userinfo',
      component: () => import("@/views/Admin/UserInfo.vue"),
      meta: {
        title: 'userinfo'
      }
    },
    {
      path: 'changepwd',
      name: 'changepwd',
      component: () => import("@/views/Admin/ChangPwd.vue"),
      meta: {
        title: 'changepwd'
      }
    },
    {
      path: "refreshview",  //刷新
      name: "refreshview",
      component: () => import("@/views/RefreshView.vue"),
      meta: {
        title: 'home',
      }
    },
    ]
  },
  {
    path: "/404",
    name: "404",
    component: _404,
  },
  // {
  //   //匹配其他形式的任何路由
  //   path: "/:path(.*)+",
  //   redirect: "/404",
  // }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});


//路由守卫
//根据token来判断是否登录，如果没有登录则要跳到登录的路由
//需要注意：当路由是登录路由时需要排除
router.beforeEach((to, from) => {
  if (!Cookies.get("token") && to.path != '/login') {
    ElMessageBox.alert('token值已失效，请重新登录', '提示', {
      confirmButtonText: 'OK',
      callback: (action) => { 
        router.replace({ path: "/login", query: { path: to.fullPath } })
      }
    })
    return false
  }
  return true
})

export default router;
